package com.qyhl.school.school.reporter.publish;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.web.RichEditor;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.AndroidBug5497Workaround;
import com.qyhl.webtv.commonlib.utils.ninephotolayout.BGASortableNinePhotoLayout;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static android.content.ClipDescription.MIMETYPE_TEXT_PLAIN;

@Route(path = ARouterPathConstant.SCHOOL_REPORTER_PUBLISH)
public class SchoolReportPublishActivity extends BaseActivity
        implements SchoolReportPublishContract.SchoolReportPublishView, BGASortableNinePhotoLayout.Delegate {
    @BindView(R2.id.button_bold)
    ImageView buttonBold;
    @BindView(R2.id.button_underline)
    ImageView buttonUnderline;
    @BindView(R2.id.button_list_ul)
    ImageView buttonListUl;
    @BindView(R2.id.button_list_ol)
    ImageView buttonListOl;
    @BindView(R2.id.title_name)
    EditText titleName;
    @BindView(R2.id.school_name)
    EditText schoolName;
    @BindView(R2.id.author_name)
    EditText authorName;
    @BindView(R2.id.rich_Editor)
    RichEditor richEditor;
    @BindView(R2.id.NinePhotoLayout)
    BGASortableNinePhotoLayout NinePhotoLayout;

    private SchoolReportPublishPresenter mPresenter;
    /**
     * 上传token
     */
    private UpTokenBean mUpToken;
    /**
     * 图片多选
     */
    public static final int CHOOSE_REQUEST = 200;

    public static final int CHOOSE_COVER_REQUEST = 201;

    private String upTitle, upSchool, upAuthor, upCover;

    private String username;

    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();

    @Override
    protected int getContentView() {
        return R.layout.activity_school_reporter_publish;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new SchoolReportPublishPresenter(this);
        NinePhotoLayout.setDelegate(this);
        AndroidBug5497Workaround.assistActivity(findViewById(android.R.id.content));
        initEditor();
        mPresenter.getToken(false);
    }

    private void initEditor() {
        //输入框显示字体的大小
        richEditor.setEditorFontSize(16);
        //输入框显示字体的颜色
        richEditor.setEditorFontColor(getResources().getColor(R.color.rich_editor_txt));
        //输入框文本padding
        richEditor.setPadding(8, 8, 8, 8);
        //输入提示文本
        richEditor.setPlaceholder("稿件正文");

    }

    @Override
    protected void setListener() {
        richEditor.setOnDecorationChangeListener((text, types) -> {
            ArrayList<String> flagArr = new ArrayList<>();
            for (int i = 0; i < types.size(); i++) {
                flagArr.add(types.get(i).name());
            }

            if (flagArr.contains("BOLD")) {
                buttonBold.setImageResource(R.mipmap.bold_);
            } else {
                buttonBold.setImageResource(R.mipmap.bold);
            }

            if (flagArr.contains("UNDERLINE")) {
                buttonUnderline.setImageResource(R.mipmap.underline_);
            } else {
                buttonUnderline.setImageResource(R.mipmap.underline);
            }


            if (flagArr.contains("ORDEREDLIST")) {
                buttonListUl.setImageResource(R.mipmap.list_ul);
                buttonListOl.setImageResource(R.mipmap.list_ol_);
            } else {
                buttonListOl.setImageResource(R.mipmap.list_ol);
            }

            if (flagArr.contains("UNORDEREDLIST")) {
                buttonListOl.setImageResource(R.mipmap.list_ol);
                buttonListUl.setImageResource(R.mipmap.list_ul_);
            } else {
                buttonListUl.setImageResource(R.mipmap.list_ul);
            }
        });
    }

    @Override
    public void postResult(boolean isSuccess, String msg) {
        dismissLoading();
        showToast(msg);
        if (isSuccess) {
            finish();
        }
    }

    private void checkData() {
        upTitle = titleName.getText().toString();
        if (StringUtils.isEmpty(upTitle)) {
            showToast("请填写稿件标题！");
            dismissLoading();
            return;
        }

        upSchool = schoolName.getText().toString();
        if (StringUtils.isEmpty(upSchool)) {
            upSchool = "";
        }

        if (NinePhotoLayout.getData() != null && NinePhotoLayout.getData().size() > 0) {
            upCover = NinePhotoLayout.getData().get(0);
        } else {
            upCover = "";
        }


        upAuthor = authorName.getText().toString();
        if (StringUtils.isEmpty(upAuthor)) {
            showToast("请填写稿件作者！");
            dismissLoading();
            return;
        }

        username = CommonUtils.getInstance().getUserName();


        String[] imageList = StringUtils.returnImageUrlsFromHtml(richEditor.getHtml());
        List<UploadBean> uploadBeans = new ArrayList<>();
        if (imageList != null && imageList.length > 0) {
            for (String s : imageList) {
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(2);
                videoCoverBean.setPath(s);
                videoCoverBean.setPostion(0);
                videoCoverBean.setViewText(s);
                uploadBeans.add(videoCoverBean);
            }

            if (StringUtils.isNotEmpty(upCover)) {
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(4);
                videoCoverBean.setPath(upCover);
                videoCoverBean.setPostion(0);
                uploadBeans.add(videoCoverBean);
            }

            QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getToken(), mUpToken.getPrefix(), new UploadResultListener() {
                @Override
                public void uplaodError() {
                    dismissLoading();
                    showToast("上传图片出错");
                }

                @Override
                public void uploadSuccess(List<UploadBean> files) {
                    parseData(files);
                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        } else {
            if (StringUtils.isNotEmpty(upCover)) {
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(4);
                videoCoverBean.setPath(upCover);
                videoCoverBean.setPostion(0);
                uploadBeans.add(videoCoverBean);
                upImage(uploadBeans);
            } else {
                mPresenter.doPost(username, richEditor.getHtml(), upTitle, upSchool, upAuthor, "");
            }
        }
    }

    private void upImage(List<UploadBean> uploadBeans) {
        if (mUpToken == null) {
            mPresenter.getToken(true);
            return;
        }
        QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getToken(), mUpToken.getPrefix(), new UploadResultListener() {
            @Override
            public void uplaodError() {
                dismissLoading();
                showToast("上传图片出错");
            }

            @Override
            public void uploadSuccess(List<UploadBean> files) {
                parseData(files);
            }

            @Override
            public void uploadPre(double percent) {

            }
        });
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mUpToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            dismissLoading();
            showToast("提交失败！");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> resultList;
        if (requestCode == CHOOSE_REQUEST) {
            resultList = PictureSelector.obtainMultipleResult(data);
            if (resultList != null && resultList.size() > 0) {
                for (int i = 0; i < resultList.size(); i++) {
                    String path = resultList.get(i).getCompressPath();
                    richEditor.insertImage(path, "dachshund");
                    richEditor.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (richEditor != null) {
                                richEditor.scrollToBottom();
                            }
                        }
                    }, 200);
                }
                richEditor.focusEditor();
                showKeyboard(richEditor);
            }
        } else if (requestCode == CHOOSE_COVER_REQUEST) {
            resultList = PictureSelector.obtainMultipleResult(data);
            if (resultList != null && resultList.size() > 0) {
                selectedList.clear();
                selectedList.addAll(resultList);
            }
            ArrayList<String> select = new ArrayList<>();

            for (int i = 0; i < selectedList.size(); i++) {
                select.add(selectedList.get(i).getCompressPath());
            }

            NinePhotoLayout.setData(select);
        }
    }


    @OnClick({R2.id.back_btn, R2.id.post_btn, R2.id.button_image, R2.id.button_bold, R2.id.button_underline, R2.id.button_list_ul, R2.id.button_list_ol, R2.id.button_rich_undo, R2.id.button_rich_do})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.post_btn) {
            hideKeyboard(view.getWindowToken());
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        showLoading();
                        checkData();
                    } else {
                        showToast("尚未登录或登录已失效！");
                        RouterManager.routerLogin(SchoolReportPublishActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });
        } else if (id == R.id.button_image) {
            selectImage();
        } else if (id == R.id.button_bold) {
            againEdit();
            richEditor.setBold();
        } else if (id == R.id.button_underline) {
            againEdit();
            richEditor.setUnderline();
        } else if (id == R.id.button_list_ul) {//加带点的序列号
            againEdit();
            richEditor.setBullets();
        } else if (id == R.id.button_list_ol) {//加带数字的序列号
            againEdit();
            richEditor.setNumbers();
        } else if (id == R.id.button_rich_undo) {
            richEditor.undo();
        } else if (id == R.id.button_rich_do) {
            richEditor.redo();
        }
    }

    /**
     * 选择图片
     */
    private void selectImage() {
        PictureSelector.create(SchoolReportPublishActivity.this)
                .openGallery(PictureMimeType.ofImage())//仅图片
                .imageSpanCount(4)//每行显示4张
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)//单选
                .isCamera(true)//允许使用相机
                .previewImage(true)//允许预览图片
                .isZoomAnim(true)
                .circleDimmedLayer(false)//圆形裁剪
                .withAspectRatio(1, 1)
                .freeStyleCropEnabled(true)
                .enableCrop(false)
                .compress(true)
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(CHOOSE_REQUEST);
    }

    private void againEdit() {
        //如果第一次点击例如加粗，没有焦点时，获取焦点并弹出软键盘
        richEditor.focusEditor();
        showKeyboard(richEditor);
    }

    /**
     * 解析替换html数据
     *
     * @param files
     */
    private void parseData(List<UploadBean> files) {
        String htmlStr = richEditor.getHtml();
        String mCoverImageUrl = "";
        for (int i = 0; i < files.size(); i++) {
            UploadBean file = files.get(i);
            if (file.getType() == 2) {
                htmlStr = htmlStr.replace(file.getViewText(), file.getUrl());
            }
            if (file.getType() == 4) {
                mCoverImageUrl = file.getUrl();
            }
        }
        dismissLoading();
        mPresenter.doPost(username, htmlStr, upTitle, upSchool, upAuthor, mCoverImageUrl);
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                //把获取到的内容打印出来
                getPasteData();
            }
        });
    }

    private void getPasteData() {
        String pasteData = "";
        ClipboardManager clipboard = (ClipboardManager)
                getSystemService(Context.CLIPBOARD_SERVICE);

        if (!(clipboard.hasPrimaryClip()) && clipboard.getPrimaryClip() != null) {
            //剪贴板无内容
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
            pasteData = (String) item.getText();
            Log.e("ApiResult1", pasteData);
        } else if (clipboard.getPrimaryClipDescription() != null && !(clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))) {
            //有内容，但不是文本内容
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
            pasteData = item.getText().toString();
            Log.e("ApiResult3", pasteData);
        } else if (clipboard.getPrimaryClip() != null) {
            //文本内容
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
            pasteData = item.getText().toString();
            Log.e("ApiResult2", pasteData);
        }
        if (!StringUtils.isEmpty(pasteData)) {
            ClipData clip = ClipData.newPlainText("simple text", pasteData);
            clipboard.setPrimaryClip(clip);
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        PictureSelector.create(SchoolReportPublishActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(CHOOSE_COVER_REQUEST);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {

    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        MNImageBrowser.showImageBrowser(this, view, position, models);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }

}
